/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.thinktank.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.thinktank.domain.Capital;
import com.fzhucc.modules.thinktank.domain.Company;
import com.fzhucc.modules.thinktank.domain.CompanyMsgBox;
import com.fzhucc.modules.thinktank.domain.dto.CapitalMsgBoxDto;
import com.fzhucc.modules.thinktank.domain.dto.CompanyBoxSeekDto;
import com.fzhucc.modules.thinktank.domain.dto.CompanyMsgBoxDto;
import com.fzhucc.modules.thinktank.domain.dto.CompanyMsgBoxQueryCriteria;
import com.fzhucc.modules.thinktank.repository.CompanyMsgBoxRepository;
import com.fzhucc.modules.thinktank.repository.CompanyRepository;
import com.fzhucc.modules.thinktank.service.mapstruct.CompanyMsgBoxMapper;
import com.fzhucc.utils.FileUtil;
import com.fzhucc.utils.PageUtil;
import com.fzhucc.utils.QueryHelp;
import com.fzhucc.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-03-10
 **/
@Service
@RequiredArgsConstructor
public class CompanyMsgBoxService {

    private final CompanyMsgBoxRepository companyMsgBoxRepository;
    private final CompanyMsgBoxMapper companyMsgBoxMapper;

    private final CompanyRepository companyRepository;

    public Map<String, Object> queryAll(CompanyMsgBoxQueryCriteria criteria, Pageable pageable) {
        Page<CompanyMsgBox> page = companyMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<CompanyMsgBoxDto> map = page.map(companyMsgBoxMapper::toDto);
        List<CompanyMsgBoxDto> list = map.getContent();
        if (list != null) {
            for (CompanyMsgBoxDto companyMsgBoxDto : list) {
                Optional<Company> res = companyRepository.findById(companyMsgBoxDto.getCompanyId());
                if (res.isPresent()) {
                    companyMsgBoxDto.setCompany(res.get());
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<CompanyMsgBoxDto> queryAll(CompanyMsgBoxQueryCriteria criteria) {
        return companyMsgBoxMapper.toDto(companyMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public CompanyMsgBoxDto findById(Integer id) {
        CompanyMsgBox companyMsgBox = companyMsgBoxRepository.findById(id).orElseGet(CompanyMsgBox::new);
        ValidationUtil.isNull(companyMsgBox.getId(), "CompanyMsgBox", "id", id);
        return companyMsgBoxMapper.toDto(companyMsgBox);
    }

    @Transactional(rollbackFor = Exception.class)
    public CompanyMsgBoxDto create(CompanyMsgBox resources) {
        return companyMsgBoxMapper.toDto(companyMsgBoxRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(CompanyMsgBox resources) {
        CompanyMsgBox companyMsgBox = companyMsgBoxRepository.findById(resources.getId()).orElseGet(CompanyMsgBox::new);
        ValidationUtil.isNull(companyMsgBox.getId(), "CompanyMsgBox", "id", resources.getId());
        companyMsgBox.copy(resources);
        companyMsgBoxRepository.save(companyMsgBox);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            companyMsgBoxRepository.deleteById(id);
        }
    }

    public void download(List<CompanyMsgBoxDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CompanyMsgBoxDto companyMsgBox : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("上市公司id", companyMsgBox.getCompanyId());
            map.put("咨询内容", companyMsgBox.getContent());
            map.put("联系方式", companyMsgBox.getPhone());
            map.put("咨询时间", companyMsgBox.getConsultationTime());
            map.put("咨询人姓名", companyMsgBox.getName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    public CompanyMsgBoxDto seek(CompanyBoxSeekDto resources) {
        CompanyMsgBox companyMsgBox = new CompanyMsgBox();
        Optional<Company> res = companyRepository.findById(resources.getCompanyId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到该上市公司");
        }
        companyMsgBox.setCompanyId(resources.getCompanyId());
        companyMsgBox.setPhone(resources.getPhone());
        companyMsgBox.setConsultationTime(new Timestamp(new Date().getTime()));
        companyMsgBox.setContent(resources.getContent());
        companyMsgBox.setName(resources.getName());
        CompanyMsgBox companyMsgBox1 = companyMsgBoxRepository.save(companyMsgBox);
        return companyMsgBoxMapper.toDto(companyMsgBox1);
    }
}